package com.lucaswangdev.logindemo.constant.common;

import com.lucaswangdev.logindemo.exception.BusinessException;
import lombok.Data;

@Data
public class BaseResultDTO<T> extends BaseDTO {

    private boolean success = true;

    private T data;

    private String errorCode;

    private String errorMsg;

    public boolean isSuccessAndData() {
        return isSuccess() && data != null;
    }

    public boolean isFailure() {
        return !isSuccess();
    }

    public String getErrorMsg(){
        return  errorMsg;
    }
    public static <T> BaseResultDTO<T> newErrorResult(ErrorInfo errorInfo) {
        return newErrorResult(errorInfo.getErrorCode(), errorInfo.getErrorMsg());
    }

    public static <T> BaseResultDTO<T> newErrorResult(String errorCode, String errorMsg) {
        BaseResultDTO<T> errorResult = new BaseResultDTO<>();
        errorResult.setSuccess(false);
        errorResult.setErrorCode(errorCode);
        errorResult.setErrorMsg(errorMsg);
        return errorResult;
    }

    public static <T> BaseResultDTO<T> newSuccessResult(T data) {
        BaseResultDTO<T> resultDTO = new BaseResultDTO<>();
        resultDTO.setSuccess(true);
        resultDTO.setData(data);
        return resultDTO;
    }

    public static <T> BaseResultDTO<T> newSuccessResult() {
        BaseResultDTO<T> resultDTO = new BaseResultDTO<>();
        resultDTO.setSuccess(true);
        return resultDTO;
    }

    public T getData(){
        if(this.success) {
            return data;
        } else {
            throw new BusinessException(errorCode, errorMsg);
        }
    }

}
